package com.sita.tboard.roadtrust.helper;

import android.text.TextUtils;

import com.sita.bike.model.Orgpicname;
import com.sita.bike.persistence.RtResourceEntity;
import com.sita.bike.persistence.RtResourceEntityDao;
import com.sita.bike.rest.RestClient;
import com.sita.bike.rest.model.Audio;
import com.sita.bike.rest.model.Location;
import com.sita.bike.rest.model.Picture;
import com.sita.bike.rest.model.RtResource;
import com.sita.bike.rest.model.RtResourceListRequest;
import com.sita.bike.rest.model.request.ResourceListByAccountRequest;
import com.sita.bike.rest.model.response.RtResourcesList4AccountResponse;
import com.sita.bike.rest.model.response.RtResourcesListResponse;
import com.sita.bike.support.GlobalContext;
import com.sita.bike.utils.AccountUtils;
import com.sita.bike.utils.LocalStorage;
import com.sita.tboard.roadtrust.event.RtResourceRefreshEvent;
import com.sita.tboard.ui.tools.L;

import java.util.List;

import de.greenrobot.event.EventBus;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

/**
 * Created by xiaodong on 16/3/23.
 */
public class RtResourceNetworkHelper {

    // define the authorId
    private static String authorId = "";

    private static class RtResourceNetworkHelperHolder {
        private static RtResourceNetworkHelper INSTANCE = new RtResourceNetworkHelper();
    }

    private RtResourceNetworkHelper() {
    }

    public static RtResourceNetworkHelper getInstance() {
        return getInstance("");
    }

    public static RtResourceNetworkHelper getInstance(String id) {
        authorId = id;
        return RtResourceNetworkHelperHolder.INSTANCE;
    }

    public void refreshResourceList() {
        long start = LocalStorage.getRtRefreshTime();
        getResourceList(15, 0, start, System.currentTimeMillis());
    }

    private void getAllResourceList(Integer pageSize, final Integer page, Long startTime,
                                    final Long endTime) {
        RtResourceListRequest request = getResourceListRequest();
        request.mPageSize = String.valueOf(pageSize);
        request.mPageNumber = String.valueOf(page);
        if (startTime != null) {
            request.mStartDate = startTime;
        }
        if (endTime != null) {
            request.mEndDate = endTime;
        }
        RestClient.getRestNormalService().rtResourceList(request, new Callback<RtResourcesListResponse>() {

            @Override
            public void success(RtResourcesListResponse resp, Response response) {
                handleResponseData(resp.mData, page, endTime);
            }

            @Override
            public void failure(RetrofitError error) {
                L.e("getResourceList()", error);
            }
        });
    }

    private void getResourceListByAccountId(final Integer pageSize, final Integer page, Long startTime,
                                            final Long endTime) {
        ResourceListByAccountRequest request = getResourceListByAccountRequest();
        request.authorId = authorId;
        request.pageSize = String.valueOf(pageSize);
        request.pageNumber = String.valueOf(page);

        RestClient.getRestNormalService().rtResourceListByAccount(request, new Callback<RtResourcesList4AccountResponse>() {
            @Override
            public void success(RtResourcesList4AccountResponse listResponse, Response response) {
                if (listResponse.errorCode.equals("0")) {
                    LocalStorage.setResourceCount(listResponse.mData.count);
                    handleResponseData(listResponse.mData.resources, page, endTime);
                }
            }
            @Override
            public void failure(RetrofitError error) {
                L.e("getResourceList()ByAccountId", error);
            }
        });
    }

    public void getResourceList(Integer pageSize, final Integer page, Long startTime,
                                final Long endTime) {
        if (TextUtils.isEmpty(authorId)) {
            getAllResourceList(pageSize, page, startTime, endTime);
        } else {
            getResourceListByAccountId(pageSize, page, startTime, endTime);
        }
    }

    private void handleResponseData(List<RtResource> mData, int page, Long endTime) {
        if (mData == null || mData.isEmpty()) {
            if (page == 0) {
                EventBus.getDefault().post(new RtResourceRefreshEvent(RtResourceRefreshEvent.Mode.REFRESH).setHasData(false));
            } else {
                EventBus.getDefault().post(new RtResourceRefreshEvent(RtResourceRefreshEvent.Mode.MORE).setHasData(false));
            }
            return;
        }
        RtResourceEntityDao entityDao = GlobalContext.getDaoSession().getRtResourceEntityDao();
        List<RtResource> rtResources = mData;
        int size = rtResources.size();

        for (int i = 0; i < size; i++) {
            RtResource rtResource = rtResources.get(i);
            RtResourceEntity entity = new RtResourceEntity();
            entity.setId(Long.valueOf(rtResource.id));
            entity.setAccountId(rtResource.accountId);
            entity.setCreateDate(rtResource.createDate);
            entity.setTitle(rtResource.title);
            entity.setTrafficType(rtResource.trafficType);
            entity.setVoteCount(rtResource.voteCount);
            Location location = rtResource.location;
            if (location != null) {
                String locStr = location.longitude + "," + location.latitude;
                entity.setLocation(locStr);
            }
            entity.setShortVideo(rtResource.shortVideo);
            entity.setFullVideo(rtResource.fullVideo);
            List<Picture> thumb = rtResource.thumbnails;
            if (thumb != null && !thumb.isEmpty()) {
                StringBuilder thumbStr = new StringBuilder();
                for (int k = 0; k < thumb.size(); k++) {
                    Picture picture = thumb.get(k);
                    if (k > 0) {
                        thumbStr.append(",");
                    }
                    thumbStr.append(picture.mUrl);
                }
                entity.setThumbnails(thumbStr.toString());
            }
            List<Orgpicname> orgpicnames = rtResource.orgpicname;
            if (orgpicnames != null && !orgpicnames.isEmpty()) {
                StringBuilder orgStr = new StringBuilder();
                for (int k = 0; k < orgpicnames.size(); k++) {
                    Orgpicname orgpic = orgpicnames.get(k);
                    if (k > 0) {
                        orgStr.append(",");
                    }
                    orgStr.append(orgpic.orgpicname);
                }
                entity.setOrgpicname(orgStr.toString());
            }
            List<Picture> pictures = rtResource.pics;
            if (pictures != null && !pictures.isEmpty()) {
                StringBuilder pictureStr = new StringBuilder();
                for (int k = 0; k < pictures.size(); k++) {
                    Picture picture = pictures.get(k);
                    if (k > 0) {
                        pictureStr.append(",");
                    }
                    pictureStr.append(picture.mUrl);
                }
                entity.setPics(pictureStr.toString());
            }
            List<Audio> audios = rtResource.audios;
            if (audios != null && !audios.isEmpty()) {
                StringBuilder audioStr = new StringBuilder();
                for (int k = 0; k < audios.size(); k++) {
                    Audio audio = audios.get(k);
                    if (k > 0) {
                        audioStr.append(",");
                    }
                    audioStr.append(audio.mUrl);
                }
                entity.setAudios(audioStr.toString());
            }

            entityDao.insertOrReplace(entity);
            if (page == 0) {
                LocalStorage.setRtRefreshTime(endTime);
                EventBus.getDefault().post(new RtResourceRefreshEvent(RtResourceRefreshEvent.Mode.REFRESH).setHasData(size > 0));
            } else {
                EventBus.getDefault().post(new RtResourceRefreshEvent(RtResourceRefreshEvent.Mode.MORE).setHasData(size > 0));
            }
        }
    }

    private ResourceListByAccountRequest getResourceListByAccountRequest() {
        ResourceListByAccountRequest request = new ResourceListByAccountRequest();
        request.accountId = AccountUtils.getAccountID();
        return request;
    }

    private RtResourceListRequest getResourceListRequest() {
        RtResourceListRequest request = new RtResourceListRequest();
        request.mAccountId = AccountUtils.getAccountID();
        request.mExcludeBlackList = true;
        request.mOnlyShowFriends = false;

        return request;
    }

}
